package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.util.ByteBufferUtil;
import com.ca.ridersclubapplication.adapter.BubbleAdapter;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.Handleable;
import com.ca.ridersclubapplication.data.entity.ListEntity;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.MessageRequester;
import com.ca.ridersclubapplication.request.dto.AccountDto;
import com.ca.ridersclubapplication.request.dto.ChatMessageDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.service.ChatService;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ca.ridersclubapplication.view.CallbackView;
import com.ea.ui.core.basic.EAInput;
import com.ea.ui.core.basic.EATextField;
import com.google.android.material.internal.ViewUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class ChatActivity extends ImmersiveActivity {

    //  用于存放草稿
    private static final Map<Long, String> map = new HashMap<>();

    //  用于标记当前是否自动滑动到底部
    public static boolean canAutoToBottom = true;

    private boolean isBlack = false;

    private Long targetId;

    private ImageView backView;
    private TextView nameView;
    private ImageView blackView;

    private RecyclerView rv;
    private BubbleAdapter adapter;

    private EditText input;
    private ImageView emjoyView;
    private TextView sendButton;

    private ProgressBar progressBar;

    private Long startId = Long.MAX_VALUE;

    private Intent chatServiceIntent;

    //  用于处理打开键盘时，RV自动上移
    private Handler handler;
    private int what = 0x123;

    //  回调视图
    private CallbackView callbackView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        //  关闭父类的自动收起键盘
        enable = false;

        initData();

        initView();

        initListener();

        loadData();
    }

    private void initData() {
        Intent intent = getIntent();
        targetId = intent.getLongExtra("targetId", 0L);
        if (targetId.equals(0L)) {
            Toast.makeText(this, "操作失败", Toast.LENGTH_SHORT).show();
            finishAfterTransition();
        }
    }

    private void initView() {

        backView = findViewById(R.id.iv_back);
        nameView = findViewById(R.id.tv_name);
        blackView = findViewById(R.id.iv_black);

        rv = findViewById(R.id.rv);
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true);
        manager.setStackFromEnd(true);
        rv.setLayoutManager(manager);
        adapter = new BubbleAdapter(this, null);
        rv.setAdapter(adapter);

        progressBar = findViewById(R.id.bar_progress);

        emjoyView = findViewById(R.id.iv_emjoy);
        input = findViewById(R.id.input_content);
        sendButton = findViewById(R.id.btn_send);


        //  是否存在草稿
        String s = map.get(targetId);
        if (s != null) {
            input.setText(s);
            checkInput();
        }

        handler = new Handler(getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == what && Boolean.TRUE.equals(msg.obj)) {
                    rv.smoothScrollToPosition(0);
                }
            }
        };


        //  创建回调视图，当有新的消息时更新视图数据
        callbackView = new CallbackView() {
            @Override
            public void update() {
                Handleable data = DataHandler.getData("HasNewMsg:" + targetId);
                if (data instanceof ListEntity) {
                    ListEntity<?> le = (ListEntity<?>) data;
                    List<ChatMessageDto> list = new ArrayList<>();
                    for (Handleable h : le.getList()) {
                        if (h instanceof ChatMessageDto) {
                            ChatMessageDto message = (ChatMessageDto) h;
                            list.add(message);
                        }
                    }

                    //  追加数据
                    adapter.appendListToBottom(list);

                    //  如果在底部，则滑动到最底部
                    if (canAutoToBottom) {
                        Message message = new Message();
                        message.what = what;
                        message.obj = canAutoToBottom;
                        handler.sendMessageDelayed(message, 250);
                    }
                }
            }
        };
        DataHandler.putView("HasNewMsg:" + targetId, callbackView);
    }

    private void initListener() {

        backView.setOnClickListener(v -> {
            map.put(targetId, Objects.requireNonNull(input.getText()).toString());
            finishAfterTransition();
        });

        blackView.setOnClickListener(v -> {
            Dialog dialog = new Dialog(this);
            @SuppressLint("InflateParams")
            View dialogView = LayoutInflater.from(this).inflate(R.layout.to_black_dialog_layout, null);
            dialog.setContentView(dialogView);
            TextView titleView = dialogView.findViewById(R.id.tv_title);
            TextView cancelButton = dialogView.findViewById(R.id.btn_cancel);
            TextView sureButton = dialogView.findViewById(R.id.btn_sure);
            String title = isBlack ? "是否移出黑名单？" : "拉黑后将不会收到该用户的消息！";
            titleView.setText(title);
            cancelButton.setOnClickListener(cl -> {
                dialog.dismiss();
            });
            sureButton.setOnClickListener(sl -> {
                //  发起请求
                if (isBlack) {
                    AccountRequester.removeBlack(this, targetId, new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                Toast.makeText(ChatActivity.this, "解除成功", Toast.LENGTH_SHORT).show();
                                isBlack = false;
                                setBlackIcon();
                            }
                            else {
                                Toast.makeText(ChatActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }
                    });
                }
                else {
                    AccountRequester.addBlack(ChatActivity.this, targetId, new AfterExecutor<String>() {
                        @Override
                        public void execute(Result<String> result) {
                            if (result.isSuccess()) {
                                Toast.makeText(ChatActivity.this, "拉黑成功", Toast.LENGTH_SHORT).show();
                                isBlack = true;
                                setBlackIcon();
                            }
                            else {
                                Toast.makeText(ChatActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }
                    });
                }
            });
            dialog.show();
        });

        sendButton.setOnClickListener(v -> {

            String content = Objects.requireNonNull(input.getText()).toString();
            if (content.isEmpty()) {
                Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
                return;
            }

            //  发起请求
            MessageRequester.sendMessage(this, targetId, content, new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {
                        //  发送成功
                        input.setText("");
                        map.remove(targetId);
                        canAutoToBottom = true;
                    }
                    else {
                        Toast.makeText(ChatActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        });

        //  滑动到顶部时，加载二十条消息记录
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                canAutoToBottom = !rv.canScrollVertically(1);
                if (!rv.canScrollVertically(-1)) {
                    progressBar.setVisibility(View.VISIBLE);
                    //  请求新的数据
                    MessageRequester.listMsgForTarget(ChatActivity.this, targetId, startId, new AfterExecutor<List<ChatMessageDto>>() {
                        @Override
                        public void execute(Result<List<ChatMessageDto>> result) {

                            List<ChatMessageDto> data = result.getData();
                            if (result.isSuccess() && data != null) {
                                //  请求成功，设置数据
                                adapter.appendListToTop(data);

                                if (data.size() > 0) {
                                    startId = data.get(data.size() - 1).getId();
                                }
                            }
                            Log.e("请求", result.getMessage());
                            //  关闭动画
                            progressBar.setVisibility(View.GONE);
                        }
                    });
                }
            }
        });

        //  输入框监听
        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                checkInput();
            }
        });

        //  输入框焦点
        input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Message message = new Message();
                    message.what = what;
                    message.obj = canAutoToBottom;
                    Log.e("传入参数", String.valueOf(message.obj));
                    handler.sendMessageDelayed(message, 250);
                }
            }
        });


        View.OnTouchListener onTouchListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (v != input && v != sendButton) {
                    KeyBoardUtil.closeKeyBoard(ChatActivity.this, input);
                }

                return false;
            }
        };
        rv.setOnTouchListener(onTouchListener);
        backView.setOnTouchListener(onTouchListener);
        blackView.setOnTouchListener(onTouchListener);
    }


    private void loadData() {

        getAccount();

        listMsgForTarget();

        isBlack();

        //  删除与该用户的未读消息
        MessageRequester.setRead(this, targetId, null);
    }

    private void checkInput() {
        String content = input.getText().toString();
        map.put(targetId, content);
        sendButton.setEnabled(!content.isEmpty());
        int color = content.isEmpty() ? R.color.secondary_text : R.color.primary;
        sendButton.setTextColor(getResources().getColor(color));
    }

    private void getAccount() {
        AccountRequester.getAccount(this, targetId, new AfterExecutor<AccountDto>() {
            @Override
            public void execute(Result<AccountDto> result) {
                AccountDto dto = result.getData();
                if (result.isSuccess()) {
                    nameView.setText(dto.getNickname());
                }
            }
        });
    }

    private void listMsgForTarget() {
        MessageRequester.listMsgForTarget(this, targetId, startId, new AfterExecutor<List<ChatMessageDto>>() {
            @Override
            public void execute(Result<List<ChatMessageDto>> result) {
                List<ChatMessageDto> data = result.getData();
                if (result.isSuccess() && data != null) {
                    //  请求成功，设置数据
                    adapter.setList(data);
                    rv.scrollToPosition(0);

                    if (data.size() > 0) {
                        startId = data.get(data.size() - 1).getId();
                        ChatService.endId = data.get(0).getId();
                    }

                    //  开启服务
                    if (chatServiceIntent == null) {
                        Log.e("ChatActivity", "启动Chat服务");
                        ChatService.activity = ChatActivity.this;
                        ChatService.targetId = targetId;
                        chatServiceIntent = new Intent(ChatActivity.this, ChatService.class);
                        startService(chatServiceIntent);
                    }
                }
                Log.e("请求", result.getMessage());
                //  关闭动画
                progressBar.setVisibility(View.GONE);
            }
        });
    }

    private void isBlack() {
        AccountRequester.isBlack(this, targetId, new AfterExecutor<Boolean>() {
            @Override
            public void execute(Result<Boolean> result) {
                if (result.isSuccess() && Boolean.TRUE.equals(result.getData())) {
                    isBlack = result.getData();
                }
                else {
                    isBlack = false;
                }
                setBlackIcon();
            }
        });
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void setBlackIcon() {
        if (isBlack) {
            blackView.setImageDrawable(getResources().getDrawable(R.drawable.ic_no_black));
        }
        else {
            blackView.setImageDrawable(getResources().getDrawable(R.drawable.ic_to_black));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DataHandler.removeView("HasNewMsg:" + targetId, callbackView);
        if (chatServiceIntent != null) {
            stopService(chatServiceIntent);
        }
    }
}